const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const graphql = require('graphql')
const mysql = require('mysql2')

const pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: 'root',
  password: '123456',
  // port: 3306,
  database: 'myemployees'
})

const app = express()

let UserFildsDesc = `
    id\n
    nickname\n
    username\n
    password\n
    avatar\n
    email\n
    phone\n
    status\n
    roleid\n`
let User = {
  name: 'User',
  fields: {
    id: { type: graphql.GraphQLID },
    nickname: { type: graphql.GraphQLString },
    username: { type: graphql.GraphQLString },
    password: { type: graphql.GraphQLInt },
    avatar: { type: graphql.GraphQLString },
    email: { type: graphql.GraphQLString },
    phone: { type: graphql.GraphQLString },
    status: { type: graphql.GraphQLString },
    roleid: { type: graphql.GraphQLString }
  },
  description: UserFildsDesc
}


const UserType = new graphql.GraphQLObjectType(User)

const UserInput = new graphql.GraphQLInputObjectType({
  ...User,
  name: 'AccountInput'
})

const AccountType = new graphql.GraphQLObjectType({
  name: 'Account',
  fields: {
    username: { type: graphql.GraphQLString },
    salary: { type: graphql.GraphQLInt },
  }
})

const queryType = new graphql.GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: graphql.GraphQLList(UserType),
      description: UserFildsDesc,
      args: {
        username: { type: graphql.GraphQLString }
      },
      resolve: function(_, { username }) {
        return new Promise((resolve, reject) => {
          const sql = username
            ? `select * from user where username="${username}";`
            : `select * from user;`
          pool.query(sql, function(err, result) {
            if (err) { console.log(err.message) }
            console.log('result', result)
            console.log(Array.isArray(result))
            resolve(result)
          })
        })
      }
    },
    account: {
      type: graphql.GraphQLList(AccountType),
      resolve: function(_, args) {
        return [
          { username: 'shanliangdeYWJ', salary: 20000, },
          { username: '小杨', salary: 20000, }]
      }
    }
  }
})

const mutationType = new graphql.GraphQLObjectType({
  name: 'Mutation',
  fields: {
    createUser: {
      type: graphql.GraphQLList(UserType),
      args: {
        input: { type: new graphql.GraphQLNonNull(UserInput) }
      },
      resolve: function(_, { input }) {
        return new Promise((resolve, reject) => {
          const sql = `insert into user set ?;`
          let poolObj = pool.query(sql, [input], function(err, result) {
            if (err) { console.log(err); reject(err) }
            resolve([input])
          })
          console.log(poolObj.sql)
        })
      }
    },
    updateUser: {
      type: graphql.GraphQLList(UserType),
      args: {
        id: { type: graphql.GraphQLInt },
        input: { type: new graphql.GraphQLNonNull(UserInput) }
      },
      resolve: function(_, { id, input }) {
        return new Promise((resolve, reject) => {
          const sql = `update user set ? where id= ? ;`
          let poolObj = pool.query(sql, [input, id], function(err, result) {
            if (err) { console.log(err); reject(err) }
            resolve([input])
          })
          console.log(poolObj.sql)
        })
      }
    },
    deleteUser: {
      type: graphql.GraphQLBoolean,
      args: {
        id: { type: graphql.GraphQLInt },
      },
      resolve: function(_, { id }) {
        return new Promise((resolve, reject) => {
          const sql = `delete from user where id= ? ;`
          let poolObj = pool.query(sql, [id], function(err, result) {
            if (err) {
              console.log(err);
              reject(false)
            }
            resolve(true)
          })
          console.log(poolObj.sql)
        })
      }
    }
  }
})

const schema = new graphql.GraphQLSchema({
  query: queryType,
  mutation: mutationType
})

app.get('/', (req, res) => {
  res.end(`<a href="/graphql">graphql</a>`)
})

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true // 是否开启调试界面，true是开启，false是不开启
}))

app.use(express.static('public'))

app.listen(8888, () => console.log('server is run on http://localhost:8888'))